# 节流
节流
# 示例
假如我们给一个按钮点击事件加上了节流,然后我们以小于间隔时间的频率连续点击按钮,那么按钮回调处理函数会每间隔一段时间执行一次。
查看源码
<template>
<button @click="click">点击我,然后在控制台查看效果</button>
</template>
<script>
import throttle from './throttle'
export default {
name: 'throttle-demo',
data () {
return {
count: 0,
last: 0
}
},
methods: {
click: throttle(function () {
let last = this.last
this.last = Date.now()
console.log('点击回调', this.count, this.last - last)
this.count++
}, 1000)
}
}
</script>
# 代码实现
/**
* 节流
* @param {*} fn 回调函数
* @param {*} time 间隔时间
*/
export default function throttle(fn, time) {
let timer
// 是否执行过了回调
let called = false
return function(...args) {
const timeout = () => {
return setTimeout(() => {
if (called === true) {
// 开始下一个计时
timer = timeout()
fn.apply(this, args)
called = false
} else {
timer = null
}
}, time)
}
called = true
if (!timer) {
fn.apply(this, args)
called = false
timer = timeout()
}
}
}